#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Oğuz Kırat
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys, os, time, webbrowser, urllib
from PyQt4 import QtCore, QtGui
from mainui import Ui_MainWindow
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s
import ui_selectdisk
import subprocess
platform=sys.platform
scriptlocation=sys.path[0]
mbyte = (1024**2)
if platform=="win32":
    from wintools import *
elif platform=="linux2":
    from linuxtools import *
class selectDisk(QtGui.QDialog, ui_selectdisk.Ui_Dialog):  
      def __init__(self):
	      QtGui.QDialog.__init__(self)
	      self.setupUi(self)
class CopyProgress(QtCore.QThread):

    procDone = QtCore.pyqtSignal(bool)
    partDone = QtCore.pyqtSignal(int)
    def run(self):
        if platform=="win32":
            cmda = 'dd.exe if="\\\\.\\'+sourceimg+'" of=\\\\.\\'+targetdisk+' bs=4M --progress' ##dd command
            wget_output = "" # buffer to hold the result
            p = subprocess.Popen(str(cmda),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
            while p.poll() is None:
                char = p.stderr.read(8)
                if char:
                    wget_output += char
                    mblist=wget_output.split('M \r')
                    if len(mblist)>3:
                        if mblist[-2].count(',')>=1:
                            completed=mblist[-2].replace(',','') #For values higher than 999 delete comma.
                        else:
                            completed=mblist[-2] 
                        self.partDone.emit((int(completed)*100)/size)
                        time.sleep(0.13) #Just to keep it more responsive

        elif platform=="linux2":
            amegabyte=(1024**2)
            completed=0
            sourceopened=open(sourceimg, 'r')
            targetopened=open(targetdisk, 'w')
            while completed<=size:
                data=sourceopened.read(amegabyte)
                targetopened.write(data)
                completed += 1
                self.partDone.emit(completed*100/size)
                time.sleep(0.13)
            scriptlocation=sys.path[0]
            

        self.procDone.emit(True)   

class Start(QtGui.QMainWindow):
        def __init__(self, parent=None):
                QtGui.QWidget.__init__(self, parent)
                self.img_src=""
                self.disk_dest=""
        def warning_dialog(self, title, text):
                QtGui.QMessageBox.warning(self, title, text, QtGui.QMessageBox.Ok)
			
        def open_file(self):
                self.selected=QtGui.QFileDialog.getOpenFileName(self, self.tr("Select an ISO or IMG file"))
                if str(self.selected).endswith('.iso') or str(self.selected).endswith('.img'):
                    self.img_src=self.selected
                elif str(self.selected)=="":
                    self.warning_dialog(self.tr("Error!"), self.tr("You didn't selected a file."))                    
                else:
                    self.warning_dialog(self.tr("Error!"), self.tr("Selected file is not a ISO or IMG file"))
				
        def select_disk(self):
                self.sd = selectDisk()
                if platform == "win32":
                    self.a = win32_PartitionUtils()
                    self.a.win32_detect_removable_drives()
                elif platform == 'linux2':
                    self.a = PartitionUtils()
                    self.a.detect_removable_drives()
                for key in self.a.drives:
                        self.sd.listWidget.insertItem(0,key)		
	  		    	    
                self.connect(self.sd.listWidget, QtCore.SIGNAL("itemClicked(QListWidgetItem *)"), self.get_disk_destination)
                self.sd.exec_()
                QtCore.pyqtSignature("bool")
        def select_dvd(self):
                self.sd = selectDisk()
                if platform == "win32":
                    self.b = win32_PartitionUtils()
                    self.b.win32_detect_dvd_drives()
                #DVD copying not supported under Linux yet.
                for key in self.b.drives:
                        self.sd.listWidget.insertItem(0,key)		
	  		    	    
                self.connect(self.sd.listWidget, QtCore.SIGNAL("itemClicked(QListWidgetItem *)"), self.get_dvd_destination)
                self.sd.exec_()
                QtCore.pyqtSignature("bool")

        def get_disk_destination(self, item):
                if item.text():
                    self.disk_dest = str(item.text())
        def get_dvd_destination(self, item):
                if item.text():
                    self.img_src = str(item.text())
        def updatePBar(self, val):
            self.ui.progressBar.setValue(val)   
            perct = "{0}%".format(val)
            self.ui.label.setText("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt; font-weight:600;\">"+perct+'</span></p></body></html>')
            self.ui.label_2.setText("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">"+self.tr("Transfered:")+str((val*size)/100)+" MB</span></p></body></html>")
            self.ui.label_3.setText("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">"+self.tr("Total:") +str(size)+"  MB</span></p></body></html>")
            self.ui.label_4.setText("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">"+self.tr("Remaining:")+str(size-((val*size)/100))+" MB</span></p></body></html>")

        def fin(self):
            from completedui import Ui_MainWindow
            self.hide()
            QtGui.QWidget.__init__(self, None)
            self.ui = Ui_MainWindow()
            self.ui.setupUi(self)
            self.show()
        def createfromimage(self):
            if self.img_src!="" and self.disk_dest!="":
                self.img_size=os.stat(self.img_src).st_size
                if platform=='win32':
                    self.disk_size = (int(self.a.drives[self.disk_dest]['size'])*(1024*1024))
                elif platform=='linux2':
                    self.disk_size = (int(self.a.drives[self.disk_dest]['size']) * (1024*1024))
                global sourceimg
                sourceimg=self.img_src
                global targetdisk
                targetdisk=self.disk_dest
                global size
                size=self.img_size/(1024**2)
                if self.img_size > self.disk_size:
                    req_size = ((self.img_size - self.disk_size) / mbyte)
                    self.warning_dialog(self.tr("Error!"), self.tr("There is no enough space on the target disk!")+"\n"+str(req_size)+self.tr("MBs more needed."))
                else:
                    self.onay=QtGui.QMessageBox.question(self, self.tr('Warning'),self.tr("You will lose all the data in the disk. Do you want to continue?"), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
                    if self.onay == QtGui.QMessageBox.Yes:
                        #First load UI for all operating systems
                        from progressui import Ui_MainWindow
                        self.hide()
                        QtGui.QWidget.__init__(self, None)
                        self.ui = Ui_MainWindow()
                        self.ui.setupUi(self)
                        self.ui.thread = CopyProgress()
                        self.ui.thread.partDone.connect(self.updatePBar)
                        self.ui.thread.procDone.connect(self.fin)
                        self.ui.thread.start()
                        self.show()
                        self.size=os.stat(self.img_src).st_size / (1024*1024)
            
                    else:
                        self.warning_dialog(self.tr("Canceled"), self.tr("Transfer canceled!"))
            else:
                self.warning_dialog(self.tr("Cannot continue."), self.tr("ISO image or target disk wasn't selected!"))
                return True
        def createfromdvd(self):
            if self.img_src!="" and self.disk_dest!="":
                if platform=='win32':
                    self.disk_size = (int(self.a.drives[self.disk_dest]['size'])*(1024*1024))
                    self.img_size = (int(self.b.drives[self.img_src]['size'])*(1024*1024))
                #DVD copying is not supported under Linux
                global sourceimg
                sourceimg=self.img_src
                global targetdisk
                targetdisk=self.disk_dest
                global size
                size=self.img_size/(1024**2)
                if self.img_size > self.disk_size:
                    req_size = ((self.img_size - self.disk_size) / mbyte)
                    self.warning_dialog(self.tr("Error!"), self.tr("There is no enough space on the target disk!")+"\n"+str(req_size)+self.tr("MBs more needed."))
                else:
                    self.onay=QtGui.QMessageBox.question(self, self.tr('Warning'),self.tr("You will lose all the data in the disk. Do you want to continue?"), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
                    if self.onay == QtGui.QMessageBox.Yes:
                        #First load UI for all operating systems
                        from progressui import Ui_MainWindow
                        self.hide()
                        QtGui.QWidget.__init__(self, None)
                        self.ui = Ui_MainWindow()
                        self.ui.setupUi(self)
                        self.ui.thread = CopyProgress()
                        self.ui.thread.partDone.connect(self.updatePBar)
                        self.ui.thread.procDone.connect(self.fin)
                        self.ui.thread.start()
                        self.show()
                        self.size=os.stat(self.img_src).st_size / (1024*1024)
            
                    else:
                        self.warning_dialog(self.tr("Canceled!"), self.tr("Transfer canceled!"))
            else:
                self.warning_dialog(self.tr("Cannot continue."), self.tr("CD/DVD drive or target disk wasn't selected!"))
                return True
        @QtCore.pyqtSignature("bool")
        def formatting(self):
                    self.onay=QtGui.QMessageBox.question(self, self.tr('Warning'),self.tr("You will lose all the data in the disk. Do you want to continue?"), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
                    if self.onay == QtGui.QMessageBox.Yes:
                        self.formatdisk=self.ui.comboBox.currentText()
                        cmda="Echo E | format "+self.formatdisk+": /q /fs:FAT32"
                        #Kill dd process before format
                        p = subprocess.Popen(str('taskkill /f /im dd.exe'),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)   
                        p = subprocess.Popen(str(cmda),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)   
                        p = subprocess.Popen(str(cmda),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
                        self.warning_dialog(self.tr("Format Completed"), self.tr("Format completed, if it didn't work, try another format and partitioning tool to use your device."))

        def backtomain(self):
            from mainui import Ui_MainWindow
            self.hide()
            QtGui.QWidget.__init__(self, None)
            self.ui = Ui_MainWindow()
            self.ui.setupUi(self)
            self.show()
            QtCore.QObject.connect(self.ui.Btn_cddvd, QtCore.SIGNAL("clicked()"), self.cddvd)
            QtCore.QObject.connect(self.ui.Btn_isoimg, QtCore.SIGNAL("clicked()"), self.isoimg)
            QtCore.QObject.connect(self.ui.Btn_format, QtCore.SIGNAL("clicked()"), self.formatpage)
            self.img_src=""
            self.disk_dest=""
        def cddvd(self):
            from cddvdui import Ui_MainWindow
            self.hide()
            QtGui.QWidget.__init__(self, None)
            self.ui = Ui_MainWindow()
            self.ui.setupUi(self)
            self.show()
            QtCore.QObject.connect(self.ui.Btn_Back, QtCore.SIGNAL("clicked()"), self.backtomain)
            QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"), self.select_dvd)
            QtCore.QObject.connect(self.ui.pushButton_2, QtCore.SIGNAL("clicked()"), self.select_disk)
            QtCore.QObject.connect(self.ui.Btn_cddvdStart, QtCore.SIGNAL("clicked()"), self.createfromdvd)

        def isoimg(self):
            from isoimgui import Ui_MainWindow
            self.hide()
            QtGui.QWidget.__init__(self, None)
            self.ui = Ui_MainWindow()
            self.ui.setupUi(self)
            self.show()
            if platform=="win32":
                QtCore.QObject.connect(self.ui.Btn_Back, QtCore.SIGNAL("clicked()"), self.backtomain)
            else:
                self.ui.Btn_Back.hide()
                self.ui.cdvdlabel.setText(_fromUtf8("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'Myriad Pro\'; font-size:26pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:24pt;\">"+self.tr("USBTransfer")+"</span></p></body></html>"))
                self.ui.cdvdlabel.setGeometry(QtCore.QRect(5, 4, 211, 41))
                self.ui.transferCDlabel.setText(_fromUtf8("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"right\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\"> Oğuz Kırat</span></p></body></html>"))

            QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"), self.open_file)
            QtCore.QObject.connect(self.ui.pushButton_2, QtCore.SIGNAL("clicked()"), self.select_disk)
            QtCore.QObject.connect(self.ui.Btn_cddvdStart, QtCore.SIGNAL("clicked()"), self.createfromimage)
        def formatpage(self):
            if platform=='win32':
                from formatuiwin import Ui_MainWindow
                self.hide()
                QtGui.QWidget.__init__(self, None)
                self.ui = Ui_MainWindow()
                self.ui.setupUi(self)
                self.show()
                QtCore.QObject.connect(self.ui.Btn_Back, QtCore.SIGNAL("clicked()"), self.backtomain)
                QtCore.QObject.connect(self.ui.Btn_formatStart, QtCore.SIGNAL("clicked()"), self.formatting)


        def languageselector(self, parent=None):
            QtGui.QWidget.__init__(self, None)
            from langselectui import Ui_MainWindow
            self.ui = Ui_MainWindow()
            self.ui.setupUi(self)
            self.show()
            QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"), self.loadlanguage)
            try:
                con=urllib.urlopen("http://usbaktarici.googlecode.com/svn/trunk/version")
                data=con.read()
                con.close()
                if int(data)>210:
                        self.onay=QtGui.QMessageBox.question(self, _fromUtf8('Warning'),_fromUtf8("New version is available, do you want to download?"), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
                        if self.onay == QtGui.QMessageBox.Yes:
                            webbrowser.open("http://www.oguzkirat.com/usb-transfer")
            except:
                pass


        def loadlanguage(self):
            self.selectedlanguage=self.ui.langBox.currentText()
            print self.selectedlanguage
            if self.selectedlanguage!="English":
                translator = QtCore.QTranslator(app)
                translator.load("lang/"+self.selectedlanguage+".qm")
                app.installTranslator(translator)
            if platform=="win32":
                self.backtomain()
            else:
                self.isoimg()
if __name__ == "__main__":
    app= QtGui.QApplication(sys.argv)
    myapp = Start()
    myapp.languageselector()
    myapp.show()
    sys.exit(app.exec_())

